#!/usr/bin/env python3
"""
DeepSeek 命令行聊天工具
使用DeepSeek API进行对话
"""

import requests
import json
import sys
import os

class DeepSeekChat:
    def __init__(self, api_key):
        self.api_key = api_key
        self.api_url = "https://api.deepseek.com/v1/chat/completions"
        self.conversation_history = []
        
    def send_message(self, message):
        """发送消息到DeepSeek API并获取回复"""
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        
        # 构建对话历史
        messages = self.conversation_history.copy()
        messages.append({"role": "user", "content": message})
        
        payload = {
            "model": "deepseek-chat",
            "messages": messages,
            "temperature": 0.7,
            "max_tokens": 2048,
            "stream": False
        }
        
        try:
            response = requests.post(self.api_url, headers=headers, json=payload, timeout=30)
            response.raise_for_status()
            
            result = response.json()
            assistant_reply = result['choices'][0]['message']['content']
            
            # 更新对话历史
            self.conversation_history.append({"role": "user", "content": message})
            self.conversation_history.append({"role": "assistant", "content": assistant_reply})
            
            # 限制对话历史长度，避免token过多
            if len(self.conversation_history) > 10:
                self.conversation_history = self.conversation_history[-10:]
                
            return assistant_reply
            
        except requests.exceptions.RequestException as e:
            return f"API请求错误: {str(e)}"
        except KeyError as e:
            return f"API响应格式错误: {str(e)}"
        except Exception as e:
            return f"未知错误: {str(e)}"
    
    def start_chat(self):
        """启动交互式聊天会话"""
        print("=" * 50)
        print("DeepSeek 命令行聊天工具")
        print("输入 'quit' 或 'exit' 退出")
        print("输入 'clear' 清空对话历史")
        print("=" * 50)
        print()
        
        while True:
            try:
                user_input = input("你: ").strip()
                
                if user_input.lower() in ['quit', 'exit', 'q']:
                    print("再见！")
                    break
                elif user_input.lower() in ['clear', 'reset']:
                    self.conversation_history = []
                    print("对话历史已清空")
                    continue
                elif not user_input:
                    continue
                
                print("DeepSeek: ", end="", flush=True)
                response = self.send_message(user_input)
                print(response)
                print()
                
            except KeyboardInterrupt:
                print("\n\n再见！")
                break
            except EOFError:
                print("\n\n再见！")
                break

def main():
    # 从环境变量或命令行参数获取API密钥
    api_key = os.environ.get('DEEPSEEK_API_KEY')
    
    if not api_key and len(sys.argv) > 1:
        api_key = sys.argv[1]
    
    if not api_key:
        # 使用用户提供的API密钥
        api_key = "sk-b1280f0b9f6844629c9951d5da297473"
    
    if not api_key:
        print("错误: 未提供DeepSeek API密钥")
        print("使用方法:")
        print("  1. 设置环境变量: export DEEPSEEK_API_KEY=你的API密钥")
        print("  2. 或作为参数传递: python deepseek_chat.py 你的API密钥")
        print("  3. 或在代码中直接设置API密钥")
        sys.exit(1)
    
    chat = DeepSeekChat(api_key)
    chat.start_chat()

if __name__ == "__main__":
    main()
